import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_play_android/common/common.dart';
import 'package:flutter_play_android/common/user.dart';
import 'package:flutter_play_android/data/api/apis_service.dart';
import 'package:flutter_play_android/data/model/base_model.dart';
import 'package:flutter_play_android/data/model/wx_article_model.dart';
import 'package:flutter_play_android/ui/base/base_widget.dart';
import 'package:flutter_play_android/utils/route_util.dart';
import 'package:flutter_play_android/utils/toast_util.dart';
import 'package:flutter_play_android/widgets/like_button_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class WeChatArticleScreen extends BaseWidget {
  final int tabId;

  const WeChatArticleScreen(this.tabId, {Key? key}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> attachState() => ArticleState();
}

class ArticleState extends BaseWidgetState<WeChatArticleScreen> {
  final List<WXArticleBean> _articleList = [];

  final ScrollController _scrollController = ScrollController();
  final RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  /// 是否显示悬浮按钮
  bool _isShowFAB = false;
  int _page = 1;

  @override
  void initState() {
    setAppBarShow(false);
    showContent();
    super.initState();
  }

  @override
  AppBar? attachAppBar() => null;

  @override
  void didChangeDependencies() {
    if (_scrollController.hasClients) {
      _scrollController.addListener(() {
        if (_scrollController.position.pixels ==
            _scrollController.position.maxScrollExtent) {
          if (_scrollController.offset < 200 && _isShowFAB) {
            setState(() {
              _isShowFAB = false;
            });
          } else {
            if (_scrollController.offset >= 200 && !_isShowFAB) {
              _isShowFAB = true;
            }
          }
        }
      });
    }
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget attachContentWidget(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      child: ListView.builder(
          physics: const BouncingScrollPhysics(),
          itemCount: _articleList.length,
          controller: _scrollController,
          itemBuilder: _itemBuilder),
      onRefresh: getWXArticleList,
      onLoading: getMoreWXArticleList,
      enablePullUp: true,
      enablePullDown: true,
    );
  }

  @override
  void onClickErrorWidget() {
    _refreshController.requestRefresh();
  }

  Widget _itemBuilder(BuildContext context, int index) {
    return ItemWeChatList(_articleList[index]);
  }

  Future getWXArticleList() async {
    _page = 1;
    int _id = widget.tabId;
    apiService.getWXArticleList((WXArticleModel wxArticleModel) {
      if (wxArticleModel.errorCode == Constants.STATUS_SUCCESS) {
        _refreshController.refreshCompleted(resetFooterState: true);
        setState(() {
          _articleList.clear();
          _articleList.addAll(wxArticleModel.data?.datas ?? []);
        });
      } else {
        ToastUtil.show(msg: wxArticleModel.errorMsg ?? '');
      }
    }, (DioError error) {}, _id, _page);
  }

  Future getMoreWXArticleList() async {
    _page++;
    int _id = widget.tabId;
    apiService.getWXArticleList((WXArticleModel wxArticleModel) {
      if (wxArticleModel.errorCode == Constants.STATUS_SUCCESS) {
        if ((wxArticleModel.data?.datas?.length ?? -1) > 0) {
          _refreshController.loadComplete();
          setState(() {
            _articleList.addAll(wxArticleModel.data?.datas ?? []);
          });
        } else {
          _refreshController.loadNoData();
        }
      } else {
        _refreshController.loadFailed();
        ToastUtil.show(msg: wxArticleModel.errorMsg ?? '');
      }
    }, (DioError error) {
      _refreshController.loadFailed();
    }, _id, _page);
  }
}

class ItemWeChatList extends StatefulWidget {
  final WXArticleBean bean;

  const ItemWeChatList(this.bean, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => ItemWeChatState();
}

class ItemWeChatState extends State<ItemWeChatList> {
  @override
  Widget build(BuildContext context) {
    var bean = widget.bean;
    return InkWell(
        onTap: () {
          RouteUtil.toWebView(context, bean.title, bean.link ?? "");
        },
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.fromLTRB(10, 10, 10, 5),
              child: Row(
                children: [
                  Text(
                    '${bean.author?.isNotEmpty == true ? bean.author : bean.shareUser}',
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                    textAlign: TextAlign.start,
                  ),
                  Expanded(
                      child: Text(
                    '${bean.niceDate}',
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                    textAlign: TextAlign.end,
                  ))
                ],
              ),
            ),
            Container(
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.fromLTRB(10, 5, 10, 5),
                child: Text(
                  '${bean.title}',
                  style: const TextStyle(fontSize: 16, color: Colors.black54),
                  textAlign: TextAlign.start,
                )),
            Container(
              padding: const EdgeInsets.fromLTRB(10, 5, 10, 10),
              child: Row(
                children: [
                  Expanded(
                      child: Text(
                    (bean.superChapterName?.isNotEmpty == true &&
                            bean.chapterName?.isNotEmpty == true)
                        ? "${bean.superChapterName} / ${bean.chapterName}"
                        : '${bean.superChapterName ?? bean.chapterName}',
                    style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                    textAlign: TextAlign.start,
                  )),
                  LikeButtonWidget(
                    isLike: bean.collect ?? false,
                    onClick: () {
                      addOrCancelCollect(bean);
                    },
                  )
                ],
              ),
            ),
            const Divider(height: 1,)
          ],
        ));
  }

  /// 添加收藏或者取消收藏
  void addOrCancelCollect(item) {
    List<String>? cookies = User.singleton.cookie;
    if (cookies == null || cookies.isEmpty) {
      ToastUtil.show(msg: '请先登录~');
    } else {
      if (item.collect) {
        apiService.cancelCollection((BaseModel model) {
          if (model.errorCode == Constants.STATUS_SUCCESS) {
            ToastUtil.show(msg: '已取消收藏~');
            setState(() {
              item.collect = false;
            });
          } else {
            ToastUtil.show(msg: '取消收藏失败~');
          }
        }, (DioError error) {
          print(error.response);
        }, item.id);
      } else {
        apiService.addCollection((BaseModel model) {
          if (model.errorCode == Constants.STATUS_SUCCESS) {
            ToastUtil.show(msg: '收藏成功~');
            setState(() {
              item.collect = true;
            });
          } else {
            ToastUtil.show(msg: '收藏失败~');
          }
        }, (DioError error) {
          print(error.response);
        }, item.id);
      }
    }
  }
}
